import React, { useState } from 'react';
let prefixCls = 'sftp';
import PropTypes from 'prop-types';
import { Icon, Form, Input, Button, Switch, Popconfirm, message } from 'antd';
import { IP_RE, IP_V6, URL_RE } from '@util/constants';
import './index.less';
import * as Api from '@api/system';
import { useEffect } from 'react';

const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 18
  },
  labelAlign: 'left'
};
const Sftp = props => {
  const {
    getFieldDecorator,
    validateFields,
    setFieldsValue,
    resetFields,
    getFieldsValue
  } = props.form;
  const [buttonLoading, setButtonLoading] = useState(false);
  const validatorHost = (rules, value = '', callback) => {
    if (value && !(IP_RE.test(value) || IP_V6.test(value) || URL_RE.test(value))) {
      return callback('请输入正确格式的ipv4,ipv6和域名格式地址');
    }
    return callback();
  };
  const getSftp = async () => {
    try {
      const { data } = await Api.getSftp();
      setFieldsValue({ ...data.data.sftp });
    } catch (e) {
      message.error(e.message);
    }
  };
  const setSftp = body => {
    setButtonLoading(true);
    Api.setSftp(body)
      .then(() => {
        message.success('保存成功');
        getSftp();
      })
      .catch(e => {
        message.error(e.message);
      })
      .finally(() => {
        setButtonLoading(false);
      });
  };
  const handleSubmit = () => {
    validateFields((err, values) => {
      if (err) {
        return;
      }
      setSftp(values);
    });
  };
  const resetTing = () => {
    resetFields();
    setSftp(getFieldsValue());
  };
  useEffect(() => {
    getSftp();
  }, []);
  return (
    <div className={prefixCls}>
      <div className={`${prefixCls}-page-title`}>SFTP配置</div>
      <div className={`${prefixCls}-tips`}>
        <Icon type="info-circle" theme="twoTone" twoToneColor="#fc8e49" />
        &nbsp;
        SFTP配置：通过配置的SFTP信息，将系统产生的任务结果数据等生成文件，主动推送至目标服务器存放目录
      </div>
      <Form {...formItemLayout} className={`${prefixCls}-from`}>
        <Form.Item label=" 启用" id="ant-form-item-no-colon">
          {getFieldDecorator('enable', { valuePropName: 'checked', initialValue: false })(
            <Switch />
          )}
        </Form.Item>
        <Form.Item label="服务器地址">
          {getFieldDecorator('host', {
            rules: [
              {
                required: true,
                message: '请填写指定的服务器地址'
              },
              {
                validator: validatorHost
              }
            ]
          })(<Input placeholder="请填写指定的服务器地址" />)}
        </Form.Item>
        <Form.Item label="端口">
          {getFieldDecorator('port', {
            initialValue: 22,
            rules: [
              {
                required: true,
                message: '请填写指定的端口，默认端口22'
              }
            ]
          })(<Input placeholder="请填写指定的端口，默认端口22" />)}
        </Form.Item>
        <Form.Item label="任务结果存放目录">
          {getFieldDecorator('remoteFilePath', {
            rules: [
              {
                required: true,
                message: '请填写任务结果存放目录'
              }
            ]
          })(<Input placeholder="请填写用户家目录下的目录地址" />)}
        </Form.Item>
        <Form.Item label="探测日志存放目录">
          {getFieldDecorator('remoteLogFilePath', {
            rules: [
              {
                required: true,
                message: '请填写探测日志存放目录'
              }
            ]
          })(<Input placeholder="请填写用户家目录下的目录地址" />)}
        </Form.Item>
        <Form.Item label="账号">
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '请输入账号'
              }
            ]
          })(<Input placeholder="请输入账号" />)}
        </Form.Item>
        <Form.Item label="密码" hasFeedback>
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '请输入密码'
              }
            ]
          })(<Input.Password placeholder="请输入密码" />)}
        </Form.Item>
        <Form.Item>
          <Popconfirm
            placement="bottomLeft"
            title={'确定要重置SFTP配置？配置重置后，将不会主动推送数据文件至原本配置的地址'}
            onConfirm={resetTing}
            okText="确定"
            cancelText="取消"
          >
            <Button className="mr10">重置</Button>
          </Popconfirm>
          <Button type="primary" onClick={() => handleSubmit()} loading={buttonLoading}>
            保存配置
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
Sftp.propTypes = {
  form: PropTypes.object
};
export default Form.create()(Sftp);
